package com.service.impl;


import com.dao.OrderMapper;
import com.entity.HyFurniture;
import com.entity.HyOrder;
import com.service.HyFurnitureService;
import com.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.List;

/**
 * @program: honye-fang
 * @description:
 * @author: Baiyyy
 * @create: 2025-02-14 22:00
 **/
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private HyFurnitureService hyFurnitureService;


    //创建订单
    @Override
    public HyOrder createOrder(Long userId, Long furnitureId, Integer quantity) {
        //获取家具信息
        HyFurniture furniture = hyFurnitureService.selectHyFurnitureById(furnitureId);
        //家具价格
        BigDecimal price = furniture.getPrice();
        //订单价格
        BigDecimal orderPrice = price.multiply(BigDecimal.valueOf(quantity));
        //创建订单对象
        HyOrder hyOrder = new HyOrder();
        hyOrder.setUserId(userId);
        hyOrder.setFurnitureId(furnitureId);
        hyOrder.setPrice(orderPrice);
        hyOrder.setQuantity(quantity);
        hyOrder.setStatus("待支付");

        //订单创建时间
        hyOrder.setCreatedAt(new Timestamp(System.currentTimeMillis()));//当前时间


        //将订单保存到数据库
        orderMapper.insertOrder(hyOrder);

        //更新家具库存
        hyFurnitureService.updateStock(furnitureId,quantity);

        //返回订单对象
        return hyOrder;
    }

    //根据订单id获取订单
    @Override
    public HyOrder getOrderById(Long orderid) {
        return orderMapper.selectOrderById(orderid);
    }

    //根据用户id获取订单
    @Override
    public List<HyOrder> getOrderByUserId(Long userId) {
        return orderMapper.selectByUserId(userId);
    }

    //更新订单状态
    @Override
    public boolean updateOrderStatus(Long orderId, String status) {
        return orderMapper.updateOrderStatus(orderId,status) > 0;
    }

    //检查并取消超时订单
    @Override
    //每五分钟检查一次
    @Scheduled(cron = "0 0/5 * * * ?")
    public void checkAndCancelTimeoutOrders() {
        //获取前三十分钟的时间戳
        long threeMinutesAgo = System.currentTimeMillis() - 3 * 60 * 1000 * 10;
        //通过时间戳查询所有为超时的订单
        List<HyOrder> timeoutOrders = orderMapper.selectTimeoutOrders(new Timestamp(threeMinutesAgo));

        for (HyOrder order : timeoutOrders) {
            //只处理未支付的订单
            if ("待支付".equals(order.getStatus())){
                //更新订单状态为已取消
                updateOrderStatus(order.getId(),"已取消");
                System.out.println("超时订单已取消");
            }

        }
    }
}
